<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <!-- 添加角色对话框 -->
      <el-dialog
        title="添加角色"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="addDialogClosed"
      >
        <el-form
          :model="addForm"
          :rules="addFormRules"
          ref="addFormRef"
          label-width="80px"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRoles()">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 角色列表区域 -->
      <el-table :data="rolesList" border stripe style="width: 100%">
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="removeRightsById(scope.row, item1.id)"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二、三级权限 -->
              <el-col :span="19">
                <el-row
                  :class="[i2 !== 0 ? 'bdtop' : '', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightsById(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      closable
                      @close="removeRightsById(scope.row, item3.id)"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column fixed="right" label="操作" width="300">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="showEditDialogVisible(scope.row.id)"
              >编辑</el-button
            >
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="removeRolesById(scope.row.id)"
              >删除</el-button
            >
            <!-- 分配权限按钮 -->
            <el-button
              type="warning"
              size="mini"
              icon="el-icon-setting"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 修改角色对话框 -->
    <el-dialog title="修改角色" :visible.sync="editDialogVisible" width="50%">
      <el-form
        :model="editForm"
        :rules="addFormRules"
        ref="editFormRef"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRolesInfo()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightDialogClosed"
    >
      <el-tree
        :data="rightsList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        :default-checked-keys="defKeys"
        default-expand-all
        ref="treeRef"
      >
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rolesList: [], // 角色列表
      addDialogVisible: false, // 添加角色的对话框显示隐藏
      addForm: {
        roleName: "", // 角色名称
        roleDesc: "", // 角色描述
      }, // 添加角色
      addFormRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "角色名称长度在2~10个字符之间",
            trigger: ["blur", "change"],
          },
        ],
        roleDesc: [
          {
            max: 10,
            message: "角色描述不能大于10个字符",
            trigger: ["blur", "change"],
          },
        ],
      },
      editDialogVisible: false, // 编辑角色的对话框显示隐藏
      editForm: {},
      setRightDialogVisible: false, // 分配权限的对话框显示隐藏
      rightsList: [], // 权限数据
      treeProps: {
        label: "authName",
        children: "children",
      }, // el-树形控件
      roleId: null,
      defKeys: [], // 默认选中的值
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    // 获取角色列表数据
    getRolesList() {
      let that = this;
      that.$http.get("roles").then((res) => {
        if (res.data.meta.status !== 200)
          return that.$message.error("获取角色列表数据失败");
        that.rolesList = res.data.data;
        // console.log(that.rolesList);
      });
    },
    // 监听添加角色对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    // 添加角色按钮
    addRoles() {
      let that = this;
      that.$refs.addFormRef.validate((valid) => {
        if (!valid) return;
        that.$http.post("roles", that.addForm).then((res) => {
          if (res.data.meta.status !== 201)
            return that.$message.error("添加角色失败");
          that.$message.success("添加角色成功");
          that.addDialogVisible = false;
          that.getRolesList();
        });
      });
    },
    // 编辑角色对话框
    showEditDialogVisible(id) {
      let that = this;
      this.$http.get("roles/" + id).then((res) => {
        if (res.data.meta.status !== 200) {
          return that.$message.error("查询角色信息失败！");
        }
        that.editForm = res.data.data;
      });
      that.editDialogVisible = true;
    },
    // 修改角色信息并提交
    editRolesInfo() {
      let that = this;
      that.$refs.editFormRef.validate((valid) => {
        if (!valid) return;
        let data = {
          roleName: that.editForm.roleName,
          roleDesc: that.editForm.roleDesc,
        };
        that.$http.put("roles/" + that.editForm.roleId, data).then((res) => {
          if (res.data.meta.status !== 200)
            return that.$message.error("更新角色信息失败");
          that.$message.success("更新角色信息成功");
          that.editDialogVisible = false;
          that.getRolesList();
        });
      });
    },
    // 删除用户按钮
    removeRolesById(id) {
      let that = this;
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          that.$http.delete("roles/" + id).then((res) => {
            if (res.data.meta.status !== 200)
              return that.$message.error("删除角色失败");
            that.$message.success("删除角色成功");
            that.getRolesList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 分配权限的对话框
    showSetRightDialog(role) {
      let that = this;
      that.roleId = role.id;
      that.$http.get("rights/tree").then((res) => {
        if (res.data.meta.status !== 200)
          return that.$message.error("获取权限数据失败");
        that.rightsList = res.data.data;
        that.getLeafKeys(role, this.defKeys);
      });
      this.setRightDialogVisible = true;
    },
    // 递归获取权限id
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach((item) => {
        this.getLeafKeys(item, arr);
      });
    },
    // 监听分配权限对话框的关闭事件
    setRightDialogClosed() {
      this.defKeys = [];
    },
    // 分配权限对话框的确认按钮
    allotRights() {
      let that = this;
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ]
      const idStr = keys.join(',')
      that.$http.post(`roles/${that.roleId}/rights`, {'rids': idStr}).then((res) => {
        if (res.data.meta.status !== 200)
          return that.$message.error("分配角色权限失败");
        that.$message.success("分配角色权限成功");
        that.getRolesList();
        that.setRightDialogVisible = false;
      });
    },
    // 根据Id删除对应权限
    removeRightsById(role, rid) {
      let that = this;
      this.$confirm("此操作将永久删除该权限, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          that.$http.delete(`roles/${role.id}/rights/${rid}`).then((res) => {
            if (res.data.meta.status !== 200)
              return that.$message.error("删除权限失败");
            that.$message.success("删除权限成功");
            role.children = res.data.data;
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
};
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>